package com.mju.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mju.controller.common.BaseController;
import com.mju.controller.common.JsonResult;
import com.mju.pojo.Favorites;
import com.mju.service.IFavoritesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/favorites")
@Api("收藏服务")
public class FavoritesController extends BaseController {
    @Autowired
    IFavoritesService favoritesService;

    @ApiOperation("添加收藏")
    @PostMapping("/addFavorite/{pid}")
    public JsonResult<Integer> addFavorites(@PathVariable("pid")Integer pid, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String uid = parseTokenGetUid(token);
        //执行插入操作并返回fid
        Integer data = favoritesService.addFavorites(Integer.parseInt(uid), pid);
        return new JsonResult<>(OK,data);
    }

    @ApiOperation("查询收藏")
    @GetMapping("/queryFavorites/{currentPage}/{pageSize}/{status}")
    public JsonResult<IPage<Favorites>> queryFavorites(HttpServletRequest request,
                                                       @PathVariable("currentPage") Integer currentPage,
                                                       @PathVariable("pageSize") Integer pageSize,
                                                       @PathVariable("status") Integer status) {
        String token = request.getHeader("Authorization");
        String uid = parseTokenGetUid(token);
        IPage<Favorites> pages = favoritesService.queryFavorites(Integer.parseInt(uid), currentPage, pageSize, status);
        return new JsonResult<>(OK, pages);
    }

    //处理取消收藏的请求
    @ApiOperation("取消收藏")
    @PostMapping("/updateStatus/{fid}/{status}")
    public JsonResult<Void> cancelFavorites(HttpServletRequest request,
                                            @PathVariable("fid") Integer fid,
                                            @PathVariable("status") Integer status){
        String token = request.getHeader("Authorization");
        String uid = parseTokenGetUid(token);
        favoritesService.updateFavoritesStatus(status,fid,Integer.parseInt(uid));
        return new JsonResult<>(OK);
    }

    @ApiOperation("根据用户id商品id查询收藏")
    @GetMapping("/queryFavorite/{uid}/{pid}/{status}")
    public JsonResult<Integer> queryFavorite(@PathVariable("uid") Integer uid,
                                             @PathVariable("pid") Integer pid,
                                             @PathVariable("status") Integer status) {
        Integer data = favoritesService.queryFavoriteByUidAndPid(uid, pid, status);
        return new JsonResult<>(OK, data);
    }

}
